import { login as loginAPI } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRoutes, allAsyncRoutes, anyRoutes } from '@/router/routes'
import { cloneDeep } from 'lodash'
import router, { resetRouter } from '@/router/index'

// 筛选动态路由
function filterDynamicRoutes(routes, routesName) {
  return routes.filter(item => {
    if (routesName.includes(item.name)) {
      if (item.children && item.children.length) {
        item.children = filterDynamicRoutes(item.children, routesName)
      }
      return true;
    } else {
      return false;
    }
  })
}


const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',

    roles: [],
    buttons: [],
    routes: [], // 本用户所有的路由,包括了固定的路由和下面的addRouters
    asyncRoutes: [], // 本用户的角色赋予的新增的动态路由

    // 用户管理数据
    PageList: [],
  }
}

const state = getDefaultState()

const mutations = {
  SET_USER: (state, userInfo) => {
    state.name = userInfo.name // 用户名
    state.avatar = userInfo.avatar // 头像
    state.roles = userInfo.roles // 角色列表
    state.buttons = userInfo.buttons // 按钮权限列表
    state.routes = userInfo.routes // 侧边栏菜单
  },

  SET_TOKEN(state, token) {
    state.token = token
  },

  RESET_USER(state) {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      loginAPI.login(username, password)
        .then(result => {
          const { data } = result
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  async getInfo({ commit, state }) {
    const { data } = await loginAPI.getInfo()
    // 对路由进行处理：
    // 1. 筛选动态路由
    const filterAsyncRoutes = filterDynamicRoutes(cloneDeep(allAsyncRoutes), data.routes);
    // 2. 重新注册路由
    const allRoutes = [...constantRoutes, ...filterAsyncRoutes, ...anyRoutes];
    router.addRoutes(allRoutes);
    data.routes = allRoutes;
    commit('SET_USER', data)
  },

  /* 
  重置用户信息
  */
  async resetUser({ commit, state }) {
    // 如果当前是登陆的, 请求退出登陆
    if (state.name) {
      await loginAPI.logout()
    }


    // 清除本地的token
    removeToken();
    // 清除之前注册过的路由
    resetRouter();
    // 提交重置用户信息的mutation
    commit('RESET_USER')

  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}